<!--
 * @FilePath: /web-vue/src/views/SysRole/authorizeForm.vue
 * @Description: 【角色】授权表单
-->
<template>
  <div>
    <!-- 弹出层-表单 -->
    <el-dialog
      class="edit-dialog"
      :title="'角色授权：' + editForm.role"
      :visible.sync="visible"
      :confirmLoading="confirmLoading"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      top="7vh"
    >
      <!-- 菜单树 -->
      <el-tree
        ref="menuTree"
        :data="menuTree"
        show-checkbox
        node-key="node"
        :default-expand-all="true"
        :props="{
          children: 'children',
          label: 'title',
        }"
        :check-strictly="true"
      >
      </el-tree>
      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          icon="el-icon-finished"
          @click="handleSubmit()"
          >保存
        </el-button>
        <el-button icon="el-icon-refresh-left" @click="handleCancel()"
          >取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      editForm: {
        roleId: null,
        role: null,
        description: null,
        status: null,
      },
      menuTree: [],
    };
  },

  methods: {
    // 打开【角色】表单授权窗口
    openEditForm(isShow, item) {
      this.visible = isShow;
      this.initialMenuTree(item.roleId);
      // 【角色】授权信息填充（延迟执行，确保子组件初始化）
      setTimeout(() => {
        // 赋值
        this.editForm.roleId = item.roleId;
        this.editForm.role = item.role;
        this.editForm.description = item.description;
        this.editForm.status = item.status;
      }, 1);
    },

    // 关闭【角色】表单授权窗口
    handleCancel() {
      this.visible = false;
      this.menuTree = [];
    },

    // 初始化菜单树
    initialMenuTree(roleId) {
      this.$api
        .querySysRoleMenu(roleId)
        .then((res) => {
          let { status, data } = res.data;
          if (status.code == 200) {
            this.menuTree = data;
            // 获取默认选中节点
            this.$refs.menuTree.setCheckedKeys(
              this.getDefaultCheckedNode([], this.menuTree),
              true
            );
          } else if (status.code == 403) {
            this.$message({
              message: `权限不足！${status.message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(
              `暂无数据记录！${status.message}`,
              "【角色菜单关联表】信息表",
              {
                type: "info",
                confirmButtonText: "确定",
                callback: (action) => {},
              }
            );
          }
        })
        .catch((err) => {
          console.log(`【角色菜单关联表】查询接口发生错误: ${err}`);
        });
    },

    // 提交
    handleSubmit() {
      const loading = this.$loading({
        target: document.querySelector(".edit-dialog"),
        lock: true,
        text: "正在保存，请耐心等待！",
      });

      // 请求参数
      let arr = this.$refs.menuTree
        .getCheckedNodes(false, true)
        .map((o) => o.node);
      let param = {
        roleId: this.editForm.roleId,
        menuIds: arr,
      };
      // 发起请求
      this.$api
        .authMenu(param)
        .then((res) => {
          loading.close();
          let { status, message, data } = res.data; // 响应数据
          if (status == 200) {
            this.handleCancel();
            // 提示信息
            this.$message({
              type: "success",
              message: `操作成功！${message}`,
              duration: 1680,
            });
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
            // this.$router.push("/login");
          } else {
            this.$alert(`操作失败！${message}`, "【角色】授权菜单", {
              type: "error",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }
        })
        .catch((err) => {
          loading.close();
          this.visible = false;
          console.log(`【角色】授权菜单接口发生错误：${err}`);
        });
    },

    // 递归获取默认选择的节点
    getDefaultCheckedNode(arr, treeData) {
      treeData.forEach((o) => {
        if (o.children && o.children.length > 0) {
          this.getDefaultCheckedNode(arr, o.children);
        }
        if (o.checkArr === "1") {
          arr.push(o.node);
        }
      });
      return arr;
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
